import { getReq, Router, storeCommit, storeState } from '@U/common'
import { accountLogin, accountReg, getMobile, loginOK, setMobile } from '@U/Auth'
import { MsgLoading, MsgLoadingClear } from '@C/Msg'
import { getProfileStatus } from '@P/Auth/request'

// 流水线
export const partner_login_reg = async () => {
    const form = storeState.loginForm
    setMobile(storeState.loginForm.username)
    // 如果是新账户就去注册
    if (storeState.isNewAccount) {
        await MsgLoading()
        return accountReg()
    }
    await MsgLoading('正在登录')
    // 处理账户状态
    // 登录
    const res = await accountLogin('/api/channel-agent/token/get', form)
    if (res.code === 200) {
        // 账户密码输入正确，初始化pwdErrCount状态
        storeCommit('pwdErrCount', 0)
        // 处理账户登录条件
        const canLogin = await accountStateHandle()
        if (!canLogin) return
        return loginOK()
    }
    if (res.code === 203 && res.msg === '密码错误') {
        let count = storeState.pwdErrCount
        count += 1
        storeCommit('pwdErrCount', count)
    }
}

interface IState {
    has?: boolean,
    type?: string,
    need?: boolean,
}
// 判断账户是否存在
export const hasMeiDaoAIAccount = async (mobile: string) => {
    const { data } = await getReq('/api/channel-agent/account/exist', { mobile }).finally(() => {})
    return data
}

// 处理账户状态
export const accountStateHandle = async () => {
    const { data } = await getProfileStatus().finally(() => {})
    const { profileStatus, contractStatus, coopStatus } = data
    MsgLoadingClear()
    if (profileStatus === 0 || profileStatus === 3) return Router.push('gr_auth')
    if (profileStatus === 1) return Router.push('accountReview')
    if (profileStatus === 2) {
        if (contractStatus === 0 || contractStatus === 3) return Router.push('signContract')
        if (contractStatus === 1) return Router.push('signNext')
        if (contractStatus === 2) {
            if (coopStatus === 1) return Router.push('signNext')
            if (coopStatus === 3) return Router.push('signContract')
        }
    }
    return true
}
